<script setup xmlns:x="http://www.w3.org/1999/xhtml">
import temblorBeonduty from "@/api/temblor/temblorBeonduty.js";
import {onMounted, reactive, ref} from "vue";
import MaInfo from "@/components/ma-info/index.vue"
import {Message} from "@arco-design/web-vue";
import temblorMacro from "@/api/temblor/temblorMacro.js";
import {UPLOAD_URL} from "@/config/app.js";
import user from '@/api/system/user.js'

const data = ref([])
const date = ref()
const year = ref()
const month = ref()
const column = ref([
  {
    dataIndex: 'username',
    title: '值班人员',
  },
  {
    dataIndex: 'date',
    title: '值班日期',
  },
  {
    dataIndex: 'week',
    title: '值班周',
  },

])
const loading = ref(false)
const importVisible = ref(false)
const showImport = () => {
  importVisible.value = true
}
// 换班信息
const changeShifts = ref()
// 换班备注
const changeShiftsRemark = ref()
// 当前用户可换班日期
const userBeondutyData = ref([])
const changeUserBeondutyId = ref()
const columns = [
  {
    title: '值班人员',
    dataIndex: 'username',
  },
  {
    title: '值班日期',
    dataIndex: 'duty_date',
  },
  {
    title: '值班周',
    dataIndex: 'week',
  },
  {
    title: '值班时间',
    dataIndex: 'date_range',
  },
  {
    title: '操作',
    slotName: 'optional'
  }
]
const setReminderTimeVisble = ref(false);
const setReminderTimeData = reactive({
  day: 2,
  time: "09:00"
})
// 设置提醒时间
const setReminderTime = () => {
  temblorBeonduty.getReminder().then(res => {
    setReminderTimeData.day = res.data.day
    setReminderTimeData.time = res.data.time
  })
  setReminderTimeVisble.value = true;

}


const getData = () => {
  loading.value = true;
  temblorBeonduty.getList({date: date.value}).then(res => {

    data.value = res.data.list
    year.value = res.data.date_year
    month.value = res.data.date_month
    importFormData.date = res.data.date

    loading.value = false;
  })
}
onMounted(() => {
  getData()
  getUserList()
})

const handleSelect = (user, dates, week) => {
  changeShifts.value = {
    userInfo: user,
    date: dates,
    week: week,
    username: user.username,
    shift_change_id: user.beonduty_id
  }
  temblorBeonduty.userBeonduty({
    date: date.value
  }).then(res => {
    userBeondutyData.value = res.data
  })
  visible.value = true
}
const visible = ref(false)
const handleOk = () => {
  if (!changeShiftsRemark.value) {
    Message.error('请填写备注信息');
    return
  }
  temblorBeonduty.applyShiftChange({
    title: '换班申请',
    content: changeShiftsRemark.value,
    users: [changeShifts.value.userInfo.user_id],
    apply_beonduty_id: changeUserBeondutyId.value, // 申请人值班日id
    shift_change_id: changeShifts.value.shift_change_id, // 换班日id


  }).then(res => {
    if (res.code === 200) {
      Message.success('申请成功')
      changeShifts.value = {}
      changeShiftsRemark.value = ''
    } else {
      Message.error(res.message)
    }
  })
}
const handleCancel = () => {
  changeShifts.value = {}
  changeShiftsRemark.value = ''
}
const changeUserBeondutyData = (record) => {
  changeUserBeondutyId.value = record.id
}
const reminderOk = () => {
  temblorBeonduty.setReminder({
    day: setReminderTimeData.day,
    time: setReminderTimeData.time
  }).then(res => {
    if (res.code === 200) {
      Message.success("设置成功")
      setReminderTimeVisble.value = false;
    } else {
      Message.error("设置失败")
    }
  })
}
const importFormData = reactive({
  date: "",
  filePath: ""
})
const uploadFile = (val) => {
  importFormData.filePath = val.response.data.url
}

/*  */
const userList = ref([])
const getUserList = () => {
  temblorMacro.getDutyUserList().then(res => {
    userList.value = res.data
    console.log('userList', userList.value)
  })
}
/* 被点击的item */
const clickItem = ref({})
const selectDutyMan = (item, man) => {
  clickItem.value = item
}
const confirmDate = (item, man) => {
  item.user_id = man.id
  item.username = man.username

}

const beonduty = async () => {

  // if (!importFormData.filePath || !importFormData.date) {
  //   Message.error("参数不合法");
  //   loading.value = false;
  //   return;
  // }
  try {
    const data = await temblorBeonduty.createDutyTemplate(importFormData)
    editData.value = data.data
    importFormData.date = data.date
    editVisible.value = true
  } catch {
    Message.error('新建失败')
  }
  // if (res.code === 200) {
  //   Message.success("导入成功")
  //   getData()
  //   loading.value = false;
  //
  //   return;
  // } else {
  //   Message.error(res.message)
  //   loading.value = false;
  //
  // }
}

/** editVisible editData editOk */
const editVisible = ref(false)
const editData = ref([])
const editOk = async () => {
  console.log(' importFormData.date', importFormData.date)
  try {
    await temblorBeonduty.submitDutyRoster({date: importFormData.date, content: editData.value})
    getData()
    Message.success('保存成功')
  } catch {
    Message.error('保存失败')
  } finally {
    editVisible.value = false

  }
}
/* 编辑值班表 */
const editDutyTable = () => {
  console.log('data---<>?>', data)
  console.log('data---<>?>', data)
  editData.value = data.value
  editVisible.value = true
}
</script>

<template>
  <a-card>
    <a-space>
      <a-form-item label="值班日期">
        <a-date-picker v-model="date" style="width: 200px; margin-bottom: 1rem"/>
      </a-form-item>
      <a-form-item>
        <a-button style="margin-top: -1rem" type="primary" @click="getData">查询</a-button>
      </a-form-item>
      <a-form-item>
        <a-button style="margin-top: -1rem" v-auth="['temblor:import:beonduty']" type="primary" @click="showImport">
          新建值班表
        </a-button>
      </a-form-item>
      <a-form-item>
        <a-button style="margin-top: -1rem" @click="setReminderTime" v-auth="['temblor:import:beonduty']" type="primary"
                  status="success">提醒时间设置
        </a-button>
      </a-form-item>
    </a-space>
    <a-spin :loading="loading" tip="导入中...">
      <table>
        <tr>
          <td>{{ year }}年{{ month }}月值班安排表</td>
          <td>
            <a-button type="primary" @click="editDutyTable">编辑</a-button>
          </td>
        </tr>
        <tr>
          <td></td>
          <td></td>
          <td class="date">形变、流体观测</td>
          <td class="date">地电观测</td>
          <td>地震观测</td>
          <td>应急值班</td>
        </tr>
        <tr>
          <td class="week">日 期</td>
          <td class="week">星 期</td>
          <td class="users">08:30-12:00、14:30-17:30</td>
          <td class="users">08:30-12:00、14:30-17:30</td>
          <td class="users">08:30-12:00、14:30-17:30</td>
          <td>12:00-14:30、17:30-次日08:30</td>
        </tr>
        <!-- 使用Vue的v-for指令循环渲染数据 -->
        <tr class="td_h" v-for="(item, index) in data" :key="index">
          <td class="date">{{ item.date }}</td>
          <td class="week">{{ item.week }}</td>
          <!-- 使用嵌套的v-for指令渲染用户列表 -->
          <td v-for="(user, i) in item.users" :key="i"
              :class="user.flat ? 'self' : ''"
              class="users">

            <a-button style="margin-left: 3rem;width: 120px;height: 30px">
              {{ user.username }}

            </a-button>

          </td>
        </tr>

      </table>
    </a-spin>
  </a-card>
  <a-modal v-model:visible="setReminderTimeVisble" @ok="importOk">
    <template #title>
      提醒时间设置
    </template>
    <div>
      <a-space size="large">
        提前：
        <a-radio-group v-model="setReminderTimeData.day" :options="[
            {label:'一天',value:1},
            {label:'当天',value:2}
        ]"/>
        <a-time-picker format="HH:mm" :defaultValue="setReminderTimeData.time" style="width: 130px;"/>

      </a-space>
    </div>
  </a-modal>

  <a-modal v-model:visible="importVisible" @ok="beonduty">
    <template #title>
      新建值班表
    </template>
    <div>
      <a-space size="large">
        <a-form-item label="选择年月">
          <a-month-picker style="width: 200px;" v-model="importFormData.date"/>
        </a-form-item>
        <!--        <a-form-item>-->
        <!--          <a-upload :action="UPLOAD_URL" :multiple="false" @success="uploadFile" name="upload"></a-upload>-->
        <!--        </a-form-item>-->
      </a-space>
    </div>
  </a-modal>


  <a-modal v-model:visible="editVisible" @ok="editOk" align-center width="60%">
    <template #title>
      编辑值班计划
    </template>


    <tr class="td_h" v-for="(item, index) in editData" :key="index" style="width: 100%">
      <td class="date" style="min-width: 100px;text-align: center">{{ item.date }}</td>
      <td class="week" style="min-width: 100px;text-align: center">{{ item.week }}</td>
      <!-- 使用嵌套的v-for指令渲染用户列表 -->
      <td v-for="(user, i) in item.users" :key="i"
          :class="user.flat ? 'self' : ''"
          class="users" @click="selectDutyMan(item,user)">

        <div style="height: 30px;display: flex;align-items: center;justify-content: center;min-width: 160px"
        >
          <a-dropdown>
            <a-button style="width: 120px;height: 30px">{{ user.username }}</a-button>
            <template #content>
              <a-doption @click="confirmDate(user,opt)" v-for="opt in userList" :key="opt.id">{{
                  opt.username
                }}
              </a-doption>

            </template>
          </a-dropdown>


        </div>

      </td>
    </tr>

  </a-modal>


  <!-- 换班信息确认弹出框 -->
  <a-modal fullscreen v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
    <template #title>
      确认换班信息
    </template>
    <div>
      <a-card>
        <ma-info
            :columns="column"
            :data="changeShifts"
        />
        <a-divider/>
        <h1>选择你要更换的班次（你的）</h1>
        <a-divider/>

        <a-table :columns="columns" :data="userBeondutyData">
          <template #optional="{ record }">
            <a-button @click="changeUserBeondutyData(record)">选择</a-button>

            <a-tag color="red" style="margin-left: 1rem" v-if="changeUserBeondutyId === record.id">已选择</a-tag>
          </template>
        </a-table>
        <a-form-item style="margin-top: 1rem" label="备注信息">
          <ma-editor v-model="changeShiftsRemark" :height="600"/>
        </a-form-item>
      </a-card>
    </div>
  </a-modal>
  <!-- 换班信息确认弹出框 end -->

</template>

<style scoped>
/* 表格基础样式 */
.self {
  background-color: #2a64a6;
  color: white;
}

table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  font-family: Arial, sans-serif;
  font-size: 14px;
  color: #333;
}

/* 单元格样式 */
td {
  padding: 8px;
  border: 1px solid #ddd;
  text-align: center;
}

/* 标题行样式 */
tr.title {
  background-color: #f5f5f5;
}

/* 标题文本样式 */
.title-text {
  font-size: 20px;
  font-weight: bold;
}

/* 不同列的特殊样式 */
td.date {
  text-align: left;
}

td.week {
  text-align: center;
}

td.users {
  text-align: left;
}

.td_h:hover {
  background-color: darkslateblue;
  color: white;
}

/* 斑马纹效果 */
tr:nth-child(even) {
  background-color: #f9f9f9;
}

@media (max-width: 600px) {
  table {
    width: 100%;
    font-size: 12px;
  }
}
</style>
